<script setup lang="ts">
import { ref } from 'vue'
import { useAppStore } from '@/store/modules/app'
import { useStorage } from '@/hooks/web/useStorage'
import { useRouter } from 'vue-router'
import { editUsers, getUser } from '@/api/user'
import { useValidator } from '@/hooks/web/useValidator'
import { onActivated } from 'vue'
import { showToast } from 'vant'

const appStore = useAppStore()
const { setStorage } = useStorage()
const { back } = useRouter()
const userInfo = ref({
  ...appStore.getUserInfo
})
const { isMobilePhone, isEmail } = useValidator()

onActivated(() => {
  getUser({
    userId:userInfo.value.id
  }).then((res) => {
    userInfo.value = res.data
  })
})

const onSubmit = (values: any) => {
  editUsers({
    id: userInfo.value.id,
    ...values
  }).then((res) => {
    // appStore.setUserInfo(res.data)
    // setStorage('userInfo', res.data)
    if(res){
      showToast('更新成功')
    }
  })
}
const onBack = () => {
  back()
}
</script>

<template>
  <van-nav-bar title="用户信息" fixed placeholder left-arrow @click-left="onBack"> </van-nav-bar>
  <div class="wrapper">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="userInfo.username" name="username" label="用户名" readonly />
        <van-field v-model="userInfo.departmentName" name="password" readonly label="部门" />
        <van-field v-model="userInfo.staffName" name="staffName" readonly label="岗位" />
        <van-field
          v-model="userInfo.name"
          name="name"
          label="姓名"
          :rules="[{ required: true, message: '请输入姓名' }]"
        />
        <van-field
          v-model="userInfo.phone"
          name="phone"
          label="电话"
          :rules="[
            { required: true, message: '请输入电话' },
            { validator: isMobilePhone, message: '请输入正确的手机号' }
          ]"
        />
        <van-field
          v-model="userInfo.email"
          name="email"
          label="邮箱"
          :rules="[
            { required: true, message: '请输入邮箱' },
            { validator: isEmail, message: '请输入正确的邮箱' }
          ]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 更新 </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="less" scoped>
.wrapper {
  padding: 16px 0;
}
.btnBox {
  padding: 32px 16px;
}
</style>
